package com.tinem.platform.web.auth.server.client.token;

import com.tinem.platform.module.pojo.co.JwtPropertyName;
import com.tinem.platform.web.auth.grant.client_credentials_custom.ClientCredentialsCustomAuthenticationToken;
import com.tinem.platform.web.auth.page.LoginUserInfo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className PlatformTokenEnhancer
 * @description TODO
 * @site 
 * @company 
 * @create 2020-08-31 13:59
 */
public class PlatformTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Map<String, Object>  info = new HashMap<>(accessToken.getAdditionalInformation());
        info.put(JwtPropertyName.GRANT_TYPE,authentication.getOAuth2Request().getRequestParameters().get(JwtPropertyName.GRANT_TYPE));

        if(authentication.getPrincipal() instanceof LoginUserInfo){
            LoginUserInfo loginUserInfo = (LoginUserInfo) authentication.getPrincipal();
            info.put(JwtPropertyName.USER_ID,loginUserInfo.getUsername());
            info.put("nick_name",loginUserInfo.getName());
            info.put("email",loginUserInfo.getEmail());
            info.put("mobile",loginUserInfo.getMobile());
            info.put("login_type",loginUserInfo.getLoginType());
            info.put("authority",loginUserInfo.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()));
        }else if(authentication.getUserAuthentication() instanceof ClientCredentialsCustomAuthenticationToken){
            Map<String,String> params = ((ClientCredentialsCustomAuthenticationToken) authentication.getUserAuthentication()).getParams();
            params.entrySet().forEach(e->{
                if(e.getKey().equals(JwtPropertyName.CLIENT_ID)){
                    return;
                }
                if(e.getKey().equals(JwtPropertyName.GRANT_TYPE)){
                    return;
                }
                if(e.getKey().equals("client_secret")){
                    return;
                }
                info.put(e.getKey(),e.getValue());
            });
        }
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
        return accessToken;
    }
}
